package persistency.controller;

import java.util.Collection;
import java.util.Iterator;

import model.Business;
import model.BusinessTypeEnum;
import persistency.ArgIO;
import persistency.DBFacade;

public abstract class BusinessController {

	private static DBFacade facade;

	public boolean insert(Business business,StringBuilder callableStatement, int length) {
		facade = new DBFacade();
		Object[] args = new Object[length];
		int[] argsType = new int[length];
		ArgIO[] argsIO = new ArgIO[length];
		for (int i = 0; i < args.length; i++) {
			try {
				prepare(business, args, argsType, argsIO, i);
			} catch (Exception e) {
				System.err.print(business);
				e.printStackTrace();
			}
		}
		return (facade.createObject(callableStatement.toString(), args, argsType, argsIO));

	}
	
	
	public Business getBusinessObject(Object id,StringBuilder callableStatement, BusinessTypeEnum businessType){
		Business reference = null;
		facade = new DBFacade();
		int LENGTH = 1;
		Object[] args = new Object[LENGTH];
		int[] argsType = new int[LENGTH];
		ArgIO[] argsIO = new ArgIO[LENGTH];
		for (int i = 0; i < args.length; i++) {
			try {
				args[i] = id;
				argsType[i] = java.sql.Types.CHAR;
				argsIO[i] = ArgIO.IN;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Collection<Business> list = facade.getResult(businessType,
				callableStatement.toString(), args, argsType, argsIO);
		if (!list.isEmpty()) {
			Iterator<Business> it = list.iterator();
			while (it.hasNext()) {
				reference = (Business) it.next();
			}
		}
		return reference;
	}
	
	public Collection<Business> getBusinessObjects(Object id,StringBuilder callableStatement,BusinessTypeEnum type, int idType) {
		int length = 1;
		Collection<Business> list;
		facade = new DBFacade();
		Object[] args = { ""};
		int[] argsType = new int[length];
		ArgIO[] argsIO = new ArgIO[length];
		for (int i = 0; i < args.length; i++) {
			try {
				switch (i) {
				case 0: {
					// in id char(15),
						args[i] = id;
					
					argsType[i] = idType;
					argsIO[i] = ArgIO.IN;
					break;
				}
				default:
					throw new Exception(
							"Error while creating getBusinessObjects");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		list = facade.getResult(type, callableStatement
				.toString(), args, argsType, argsIO);
		return list;
	}
	
	public Collection<Business> getBusinessObjects(StringBuilder callableStatement,BusinessTypeEnum type) {
		Collection<Business> list;
		facade = new DBFacade();
		list = facade.getResult(type, callableStatement
				.toString());
		return list;
	}
	
	public int executeMaxQuery(StringBuilder callableStatement){
		facade = new DBFacade();
		return facade.executeMaxQuery(callableStatement.toString());
	
	}
	
	public abstract void prepare(Business business, Object[] args, int[] argsType, ArgIO[] argsIO, int i)throws Exception;
}
